package action;

import entity.Member;
import exception.DuplicateUsernameException;
import exception.UserNotFoundException;
import framework.bean.factory.ObjectFactory;
import framework.mvc.annotation.Action;
import framework.mvc.annotation.Controller;
import framework.mvc.annotation.Result;
import framework.mvc.enu.ResultType;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import service.MemberService;
import util.ActionFormUtil;

@Controller
@Action(path = "/member")
public class MemberAction {

    @Action(path = "/showRegister1",forward = "/WEB-INF/page/register-1.jsp")
    public void showRegister1(){}

    @Action(path = "/showRegister2",forward = "/WEB-INF/page/register-2.jsp")
    public void showRegister2(){}

    @Action(path = "/showLogin",forward = "/WEB-INF/page/login.jsp")
    public void showLogin(){}

    @Action(path = "/regist",results = {
            @Result(name = "success",path = "/member/showRegister2.action",type = ResultType.REDIRECT),
            @Result(name = "duplicateUsername",path = "/WEB-INF/page/register-1.jsp",type = ResultType.FORWARD)
    })
    public String regist(HttpServletRequest request, HttpServletResponse response) throws ServletException {

        Member member= ActionFormUtil.parseRequest(request, Member.class);

        MemberService memberService= (MemberService) ObjectFactory.getObject("memberService");


        try {
            memberService.regist(member);

            return "success";
        } catch (DuplicateUsernameException e) {

            request.setAttribute("message",e.getMessage());

            return "duplicateUsername";
        }



    }

    @Action(path = "/login",results = {
            @Result(name = "success",path = "/subscription/check/findUnacknowledged.action",type = ResultType.REDIRECT),
            @Result(name = "userNotFound",path = "/WEB-INF/page/login.jsp",type = ResultType.FORWARD)
    })
    public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException {

        String username=request.getParameter("username");
        String password=request.getParameter("password");

        MemberService memberService= (MemberService) ObjectFactory.getObject("memberService");

        try {
            Member member=memberService.login(username,password);

            request.getSession().setAttribute("member",member);

            return "success";
        } catch (UserNotFoundException e) {

            request.setAttribute("message",e.getMessage());

            return "userNotFound";
        }


    }

    @Action(path = "/check/logout",results = @Result(path = "/showIndex.action",type = ResultType.REDIRECT))
    public String logout(HttpServletRequest request, HttpServletResponse response){

        request.getSession().invalidate();;

        return "success";
    }



}
